package com.sunny.ynhz.utils;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.sunny.ynhz.bean.RiverData;
import com.sunny.ynhz.db.RealmUtils;

import io.realm.Realm;

/**
 * Created by huhuan123 on 2018/9/6.
 *
 * @describe TODO
 */

public class GsonUtils {
    public static void putString(String tag, Object content) {
        Gson gson = new Gson();
        String gsonStr = gson.toJson(content, content.getClass());
        String userId = SPUtil.get("userId", "").toString();
        RiverData riverData = new RiverData();
        riverData.setId(userId + tag);
        riverData.setGsonStr(gsonStr);
        RealmUtils.getDeleteRealm().executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                realm.copyToRealmOrUpdate(riverData);
            }
        });
    }

    public static <T> T getInstance(String tag, Class<T> c) {
        String userId = SPUtil.get("userId", "").toString();
        String key = userId + tag;
        RiverData riverData = RealmUtils.getDeleteRealm().where(RiverData.class).equalTo("id", key).findFirst();
        if (riverData == null) {
            return null;
        }
        String gsonStr = riverData.getGsonStr();
        Gson gson = new Gson();
        Object object = gson.fromJson(gsonStr, c);
        return c.cast(object);
    }

}
